package com.sd.service.impl;

import com.sd.common.constant.CommonConstants;
import com.sd.common.utils.DateProvider;
import com.sd.common.utils.FileUtils;
import com.sd.dao.ImCollectDAO;
import com.sd.domain.ImCollect;
import com.sd.service.ImCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

/**
 * 用户管理模块的service组件实现类
 * @author yexinming
 * @date 2020/3/12
 **/
@Service
@Transactional(rollbackOn = Exception.class)
public class ImCollectServiceImpl implements ImCollectService {

    /**
     * 文件的路径类型
     */
    @Value("${collect.upload.path.type}")
    private String filePathType;
    /**
     * 文件的上传路径
     */
    @Value("${collect.upload.path.value}")
    private String filePath;

    @Autowired
    private ImCollectDAO imCollectDAO;
    /**
     * 日期辅助组件
     */
    @Autowired
    private DateProvider dateProvider;

    @Override
    public List<ImCollect> listByAgentId(String agentId) throws Exception {
        return imCollectDAO.listByAgentId(agentId);
    }

    @Override
    public Long save(ImCollect collect,MultipartFile file) throws Exception {
        //1.先文件上传
        String filePath = uploadFile(file);
        if(!StringUtils.isEmpty(filePath)){
            collect.setFilePath(filePath);
        }
        Date currentTime = dateProvider.getCurrentTime();
        //2.保存
        collect.setGmtCreate(currentTime);
        collect.setGmtModified(currentTime);
        return imCollectDAO.save(collect);
    }

    @Override
    public ImCollect getById(Long id) throws Exception {
        return imCollectDAO.getById(id);
    }

    /**
     * 文件上传
     * @param file
     * @return
     * @throws Exception
     */
    private String uploadFile(MultipartFile file) throws Exception{
        if(file == null){
            return null;
        }
        String uploadDirPath = null;
        if(CommonConstants.PathTpeEnum.RELATIVE.getValue().equals(filePathType)){
            uploadDirPath = FileUtils.getPathByRelative(filePath);
        }else {
            uploadDirPath = filePath;
        }
        String uploadFilePath = FileUtils.uploadFile(file, uploadDirPath);
        return uploadFilePath;
    }
}
